/**
 * 
 */
package org.tangram.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author han_feng
 * 
 */
public class DelegatingFilter implements Filter {

	private static final Logger logger = LoggerFactory
			.getLogger(DelegatingFilter.class);

	/**
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		logger.debug("init");
	}

	/**
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		String requestType; // 基于Servlet2.4，对filter的四种dispatcher提供支持

		String uri = ((HttpServletRequest) request).getRequestURI();

		Object forwardUri = request
				.getAttribute("javax.servlet.forward.request_uri");
		Object includeUri = request
				.getAttribute("javax.servlet.include.request_uri");
		Object errorUri = request
				.getAttribute("javax.servlet.error.request_uri");
		if (forwardUri != null) {
			requestType = "forward";
			logger.debug("[{}] {} >>> {}", new String[] { requestType,
					forwardUri.toString(), uri });
		} else if (includeUri != null) {
			requestType = "include";
			logger.debug("[{}] {} >>> {}", new String[] { requestType,
					includeUri.toString(), uri });
		} else if (errorUri != null) {
			requestType = "error";
			logger.debug("[{}] {} >>> {}",
					new String[] { requestType, errorUri.toString(), uri });
		} else {
			requestType = "request";
			logger.debug("[{}] >>> {}", requestType, uri);
		}

		chain.doFilter(request, response);
	}

	/**
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		logger.debug("destroy");
	}

}
